package cn.yywd_123.biliarchiver.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.channels.ClosedByInterruptException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Downloader {
	public static final int QUEUE_CAPACITY = 16;
	public static final ArrayBlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
	static ExecutorService threadPool = new ThreadPoolExecutor(8, 8, 1, TimeUnit.SECONDS, WORK_QUEUE);
	static Runnable task;

	static {
		Runtime.getRuntime().addShutdownHook(new Thread(Downloader::shutdown));
	}

	public static void download(URL url, Path outputPath) {
		task = () -> {
			Path fileName = outputPath.getFileName();
			try (InputStream targetReader = HttpsResponse.openConnection(url).getInputStream(); OutputStream outputWriter = Files.newOutputStream(outputPath)) {
				int i;
				while ((i = targetReader.read()) != -1) {
					outputWriter.write(i);
				}
			} catch (IOException e) {
				if (e instanceof ClosedByInterruptException) return;

				addTask(task);

				return;
			}
			System.out.println(fileName + "下载完成");
		};

		addTask(task);
	}

	static void addTask(Runnable task) {
		do {
			if (threadPool.isShutdown()) return;
		} while (WORK_QUEUE.size() == QUEUE_CAPACITY);

		threadPool.submit(task);
	}

	public static void shutdown() {
		threadPool.shutdownNow();
	}
}
